// 和动态数据有关的路由
let query = require("../model/connect")
// 用户相关路由
const express = require("express");
let router = express.Router();

// 1.添加主评论addComments
// 2.添加子评论addSubComments
// 3.获取该动态的所有评论getCommentsList

router.post("/addComments",async(req,res)=>{
    try {
        // 添加主评论
        let { uid, fid, comment } = req.body;
        let addtime = new Date().getTime();
        let result = await query(`INSERT INTO flag_detail_comments(uid,fid,comment,addtime) VALUES(${uid},${fid},'${comment}',${addtime})`);
        // console.log(result);
        if(result.affectedRows>0){
            res.json({
                // info:"添加成功",
                status:1
            });
        }else{
            res.json({
                // info:"添加成功没有数据",
                status:2
            });
        }
        
    }catch(err){
        res.json({
            // info:"添加失败",
            status:0
        });
    }

})

// 添加子评论 
router.post("/addSubComments",async (req,res)=>{
    // 添加子评论
    try{
        let { uid, fid, comment,pid } = req.body;
        let addtime = new Date().getTime();
        let result = await query(`INSERT INTO flag_detail_comments(uid,fid,comment,addtime,pid) VALUES(${uid},${fid},'${comment}',${addtime},${pid})`);
        // console.log(result)
        if(result.affectedRows>0){
            res.json({
                // info:"添加成功",
                status:1
            });
        }else{
            res.json({
                // info:"添加失败",
                status:0
            });
        }
       
    }catch(err){
        res.json({
            // info:"添加失败",
            status:0
        });
    }
   
})


router.get("/getCommentsList",async (req,res)=>{
    try{
         // 获取评论的列表
    let {fid} = req.query;
    //从flag_detail_comments表中获取评论id，用户名，用户头像，评论内容，评论添加时间
    let list = await query(`SELECT D.id,E.username,E.avatar,D.comment,D.addtime FROM flag_detail_comments D LEFT JOIN user E ON D.uid=E.id WHERE D.fid=${fid} AND D.pid=0`);
    for (let i = 0; i < list.length; i++) {
        list[i].addtime = new Date(list[i].addtime).getMonth() + 1 + "/" + new Date(list[i].addtime).getDate();

        let subList =   await query(`SELECT D.id,E.username,E.avatar,D.comment,D.addtime 
            FROM flag_detail_comments D LEFT JOIN user E ON D.uid=E.id WHERE pid=${list[i].id}`);
            for(let i = 0;i < subList.length;i++){
                subList[i].addtime = new Date(subList[i].addtime).getMonth() + 1 + "/" + new Date(subList[i].addtime).getDate();
            }
        list[i].subList = subList;
        // console.log("subList",list);
    }
// console.log(list);
    res.json({
        list,
        status:1
    })

    }catch(err){
        // console.log(err);
        res.json({
            info:"失败",
            status:0
        })

    }



})

module.exports = router;